import sys
import socket
import threading
import pyodbc
import logging
from PyQt5.QtWidgets import (
    QApplication, QMainWindow, QWidget, QVBoxLayout, QHBoxLayout,
    QLabel, QLineEdit, QPushButton, QTextEdit, QGroupBox,
    QTabWidget, QMessageBox, QFileDialog, QCheckBox, QComboBox
)
from PyQt5.QtCore import Qt, QSettings, QTimer

# 配置详细日志
logging.basicConfig(
    filename='scanner_debug.log',
    level=logging.DEBUG,
    format='%(asctime)s - %(levelname)s - %(message)s',
    filemode='w'
)
logger = logging.getLogger()

class DatabaseExplorer:
    """数据库深度检查工具"""
    @staticmethod
    def full_inspection(db_path):
        """执行完整的数据库检查"""
        try:
            conn_str = f'DRIVER={{Microsoft Access Driver (*.mdb, *.accdb)}};DBQ={db_path};'
            conn = pyodbc.connect(conn_str)
            cursor = conn.cursor()
            
            # 1. 检查所有表
            tables = cursor.tables(tableType='TABLE').fetchall()
            logger.info(f"数据库包含 {len(tables)} 张表")
            
            inspection_result = {
                'tables': {},
                'connection_test': True,
                'error': None
            }
            
            for table in tables:
                table_name = table.table_name
                logger.info(f"正在检查表: {table_name}")
                
                table_info = {
                    'columns': [],
                    'sample_data': [],
                    'row_count': 0,
                    'possible_sn_columns': []
                }
                
                try:
                    # 获取列信息
                    cursor.execute(f"SELECT TOP 1 * FROM [{table_name}]")
                    table_info['columns'] = [column[0] for column in cursor.description]
                    
                    # 获取样本数据
                    table_info['sample_data'] = cursor.execute(
                        f"SELECT TOP 3 * FROM [{table_name}]"
                    ).fetchall()
                    
                    # 获取行数
                    table_info['row_count'] = cursor.execute(
                        f"SELECT COUNT(*) FROM [{table_name}]"
                    ).fetchval()
                    
                    # 识别可能的SN列
                    possible_sn = ['SN', 'Serial', 'SerialNumber', '编号', '条码', 'Barcode', 'Code']
                    table_info['possible_sn_columns'] = [
                        col for col in table_info['columns']
                        if any(sn.lower() in col.lower() for sn in possible_sn)
                    ]
                    
                    # 如果没有找到可能的SN列，检查所有列的数据类型
                    if not table_info['possible_sn_columns']:
                        for col in table_info['columns']:
                            try:
                                sample = cursor.execute(
                                    f"SELECT TOP 1 [{col}] FROM [{table_name}] WHERE [{col}] IS NOT NULL"
                                ).fetchval()
                                if sample and any(c.isalpha() for c in str(sample)):
                                    table_info['possible_sn_columns'].append(col)
                            except:
                                continue
                
                except Exception as e:
                    logger.error(f"检查表 {table_name} 时出错: {e}")
                    table_info['error'] = str(e)
                
                inspection_result['tables'][table_name] = table_info
            
            conn.close()
            return inspection_result
            
        except Exception as e:
            logger.error(f"数据库检查失败: {e}")
            return {
                'connection_test': False,
                'error': str(e)
            }

class DatabaseManager:
    def __init__(self):
        self.connection = None
        self.db_path = ""
        self.table_info = {}
    
    def connect(self, db_path):
        """连接数据库并执行完整检查"""
        try:
            self.db_path = db_path
            conn_str = f'DRIVER={{Microsoft Access Driver (*.mdb, *.accdb)}};DBQ={db_path};'
            self.connection = pyodbc.connect(conn_str)
            logger.info(f"成功连接到数据库: {db_path}")
            
            # 执行完整检查
            self.perform_full_inspection()
            return True
        except Exception as e:
            logger.error(f"数据库连接失败: {e}")
            return False
    
    def perform_full_inspection(self):
        """执行完整的数据库检查"""
        inspection = DatabaseExplorer.full_inspection(self.db_path)
        if inspection['connection_test']:
            self.table_info = inspection['tables']
            logger.info("数据库检查完成")
            for table, info in self.table_info.items():
                logger.debug(f"表 {table} 信息: {info}")
        else:
            logger.error("数据库检查失败")
    
    def get_table_columns(self, table_name):
        """获取表的列名"""
        return self.table_info.get(table_name, {}).get('columns', [])
    
    def query_with_all_methods(self, sn, table_name):
        """尝试所有可能的查询方法"""
        if not self.connection or table_name not in self.table_info:
            logger.error("数据库未连接或表不存在")
            return None
        
        columns_to_try = self.table_info[table_name].get('possible_sn_columns', [])
        if not columns_to_try:
            columns_to_try = self.table_info[table_name].get('columns', [])
        
        logger.info(f"将尝试在以下列中查询: {columns_to_try}")
        
        cursor = self.connection.cursor()
        results = []
        
        for column in columns_to_try:
            try:
                # 方法1: 精确匹配
                query = f"SELECT * FROM [{table_name}] WHERE [{column}] = ?"
                cursor.execute(query, sn)
                exact_matches = cursor.fetchall()
                
                if exact_matches:
                    logger.info(f"在列 {column} 中找到 {len(exact_matches)} 条精确匹配记录")
                    return {
                        'data': exact_matches,
                        'columns': [col[0] for col in cursor.description],
                        'method': f"精确匹配 (列: {column})",
                        'success': True
                    }
                
                # 方法2: 模糊匹配
                query = f"SELECT * FROM [{table_name}] WHERE [{column}] LIKE ?"
                cursor.execute(query, f'%{sn}%')
                like_matches = cursor.fetchall()
                
                if like_matches:
                    logger.info(f"在列 {column} 中找到 {len(like_matches)} 条模糊匹配记录")
                    return {
                        'data': like_matches,
                        'columns': [col[0] for col in cursor.description],
                        'method': f"模糊匹配 (列: {column})",
                        'success': True
                    }
                
                # 方法3: 转换为文本后比较
                query = f"SELECT * FROM [{table_name}] WHERE CSTR([{column}]) LIKE ?"
                cursor.execute(query, f'%{sn}%')
                cast_matches = cursor.fetchall()
                
                if cast_matches:
                    logger.info(f"在列 {column} 中找到 {len(cast_matches)} 条转换后匹配记录")
                    return {
                        'data': cast_matches,
                        'columns': [col[0] for col in cursor.description],
                        'method': f"文本转换匹配 (列: {column})",
                        'success': True
                    }
                
            except Exception as e:
                logger.warning(f"查询列 {column} 时出错: {e}")
                continue
        
        # 如果所有方法都失败，返回表的前5条记录用于调试
        cursor.execute(f"SELECT TOP 5 * FROM [{table_name}]")
        sample_data = cursor.fetchall()
        
        return {
            'data': sample_data,
            'columns': [col[0] for col in cursor.description],
            'method': "无匹配，返回示例数据",
            'success': False
        }

class ScannerDebugUI(QMainWindow):
    def __init__(self):
        super().__init__()
        self.setWindowTitle("扫码枪数据库查询系统 - 终极调试版")
        self.resize(1200, 800)
        
        # 初始化组件
        self.settings = QSettings("ScannerSystem", "UltimateDebug")
        self.db_manager = DatabaseManager()
        self.server_socket = None
        self.client_socket = None
        self.tcp_mode = "server"  # 默认模式
        
        # 创建UI
        self.init_ui()
        
        # 加载设置
        self.load_settings()
        
        # 自动聚焦到SN输入框
        QTimer.singleShot(100, self.scan_input.setFocus)  # 使用定时器确保UI完全加载
    
    def init_ui(self):
        # 主布局
        main_widget = QWidget()
        main_layout = QVBoxLayout()
        main_widget.setLayout(main_layout)
        self.setCentralWidget(main_widget)
        
        # 标签页
        self.tabs = QTabWidget()
        main_layout.addWidget(self.tabs)
        
        # 创建标签页
        self.create_query_tab()
        self.create_debug_tab()
        self.create_advanced_tab()
    
    def create_query_tab(self):
        """创建查询标签页"""
        tab = QWidget()
        layout = QVBoxLayout()
        tab.setLayout(layout)
        self.tabs.addTab(tab, "数据查询")
        
        # 数据库设置
        db_group = QGroupBox("数据库设置")
        db_layout = QVBoxLayout()
        db_group.setLayout(db_layout)
        layout.addWidget(db_group)
        
        # 数据库路径
        path_layout = QHBoxLayout()
        path_layout.addWidget(QLabel("数据库路径:"))
        self.db_path_input = QLineEdit()
        self.browse_btn = QPushButton("浏览...")
        self.browse_btn.clicked.connect(self.browse_db)
        path_layout.addWidget(self.db_path_input)
        path_layout.addWidget(self.browse_btn)
        db_layout.addLayout(path_layout)
        
        # 表选择
        table_layout = QHBoxLayout()
        table_layout.addWidget(QLabel("表名:"))
        self.table_combo = QComboBox()
        self.refresh_tables_btn = QPushButton("刷新表")
        self.refresh_tables_btn.clicked.connect(self.refresh_tables)
        table_layout.addWidget(self.table_combo)
        table_layout.addWidget(self.refresh_tables_btn)
        db_layout.addLayout(table_layout)
        
        # 测试连接
        self.test_btn = QPushButton("测试数据库连接")
        self.test_btn.clicked.connect(self.test_connection)
        db_layout.addWidget(self.test_btn)
        
        # 扫描输入
        scan_group = QGroupBox("扫描查询")
        scan_layout = QVBoxLayout()
        scan_group.setLayout(scan_layout)
        layout.addWidget(scan_group)
        
        self.scan_input = QLineEdit()
        self.scan_input.setPlaceholderText("请输入或扫描SN号码")
        self.scan_input.returnPressed.connect(self.execute_query)
        scan_layout.addWidget(self.scan_input)
        
        self.query_btn = QPushButton("执行查询")
        self.query_btn.clicked.connect(self.execute_query)
        scan_layout.addWidget(self.query_btn)
        
        # 查询结果
        self.result_display = QTextEdit()
        self.result_display.setReadOnly(True)
        layout.addWidget(QLabel("查询结果:"))
        layout.addWidget(self.result_display)
    
    def create_debug_tab(self):
        """创建调试标签页"""
        tab = QWidget()
        layout = QVBoxLayout()
        tab.setLayout(layout)
        self.tabs.addTab(tab, "调试工具")
        
        # 数据库检查
        inspect_group = QGroupBox("数据库检查")
        inspect_layout = QVBoxLayout()
        inspect_group.setLayout(inspect_layout)
        layout.addWidget(inspect_group)
        
        self.inspect_btn = QPushButton("执行完整数据库检查")
        self.inspect_btn.clicked.connect(self.full_inspection)
        inspect_layout.addWidget(self.inspect_btn)
        
        self.debug_output = QTextEdit()
        self.debug_output.setReadOnly(True)
        inspect_layout.addWidget(self.debug_output)
        
        # 执行自定义SQL
        sql_group = QGroupBox("执行自定义SQL")
        sql_layout = QVBoxLayout()
        sql_group.setLayout(sql_layout)
        layout.addWidget(sql_group)
        
        self.sql_input = QTextEdit()
        self.sql_input.setPlaceholderText("输入SQL查询语句，例如: SELECT * FROM [表名] WHERE ...")
        sql_layout.addWidget(self.sql_input)
        
        self.execute_sql_btn = QPushButton("执行SQL")
        self.execute_sql_btn.clicked.connect(self.execute_custom_sql)
        sql_layout.addWidget(self.execute_sql_btn)
        
        self.sql_result = QTextEdit()
        self.sql_result.setReadOnly(True)
        sql_layout.addWidget(self.sql_result)
    
    def create_advanced_tab(self):
        """创建高级标签页"""
        tab = QWidget()
        layout = QVBoxLayout()
        tab.setLayout(layout)
        self.tabs.addTab(tab, "高级设置")
        
        # TCP设置
        tcp_group = QGroupBox("TCP扫码枪设置")
        tcp_layout = QVBoxLayout()
        tcp_group.setLayout(tcp_layout)
        layout.addWidget(tcp_group)
        
        # 模式选择
        mode_layout = QHBoxLayout()
        mode_layout.addWidget(QLabel("工作模式:"))
        self.mode_combo = QComboBox()
        self.mode_combo.addItems(["TCP服务端", "TCP客户端"])
        self.mode_combo.currentTextChanged.connect(self.change_tcp_mode)
        mode_layout.addWidget(self.mode_combo)
        tcp_layout.addLayout(mode_layout)
        
        # 服务器设置
        self.server_frame = QWidget()
        server_layout = QVBoxLayout()
        self.server_frame.setLayout(server_layout)
        
        # 服务器地址和端口
        server_addr_layout = QHBoxLayout()
        server_addr_layout.addWidget(QLabel("监听地址:"))
        self.server_host_input = QLineEdit("0.0.0.0")
        server_addr_layout.addWidget(self.server_host_input)
        server_addr_layout.addWidget(QLabel("端口:"))
        self.server_port_input = QLineEdit("12345")
        server_addr_layout.addWidget(self.server_port_input)
        server_layout.addLayout(server_addr_layout)
        
        # 服务器控制
        server_btn_layout = QHBoxLayout()
        self.start_server_btn = QPushButton("启动服务器")
        self.start_server_btn.clicked.connect(self.start_server)
        self.stop_server_btn = QPushButton("停止服务器")
        self.stop_server_btn.clicked.connect(self.stop_server)
        self.stop_server_btn.setEnabled(False)
        server_btn_layout.addWidget(self.start_server_btn)
        server_btn_layout.addWidget(self.stop_server_btn)
        server_layout.addLayout(server_btn_layout)
        
        # 客户端设置
        self.client_frame = QWidget()
        client_layout = QVBoxLayout()
        self.client_frame.setLayout(client_layout)
        
        # 客户端地址和端口
        client_addr_layout = QHBoxLayout()
        client_addr_layout.addWidget(QLabel("服务器地址:"))
        self.client_host_input = QLineEdit()
        client_addr_layout.addWidget(self.client_host_input)
        client_addr_layout.addWidget(QLabel("端口:"))
        self.client_port_input = QLineEdit()
        client_addr_layout.addWidget(self.client_port_input)
        client_layout.addLayout(client_addr_layout)
        
        # 客户端控制
        client_btn_layout = QHBoxLayout()
        self.start_client_btn = QPushButton("连接客户端")
        self.start_client_btn.clicked.connect(self.start_client)
        self.stop_client_btn = QPushButton("断开客户端")
        self.stop_client_btn.clicked.connect(self.stop_client)
        self.stop_client_btn.setEnabled(False)
        client_btn_layout.addWidget(self.start_client_btn)
        client_btn_layout.addWidget(self.stop_client_btn)
        client_layout.addLayout(client_btn_layout)
        
        # 添加服务器和客户端框架
        tcp_layout.addWidget(self.server_frame)
        tcp_layout.addWidget(self.client_frame)
        
        # 日志显示
        self.tcp_log = QTextEdit()
        self.tcp_log.setReadOnly(True)
        tcp_layout.addWidget(QLabel("TCP日志:"))
        tcp_layout.addWidget(self.tcp_log)
        
        # 设置
        settings_group = QGroupBox("系统设置")
        settings_layout = QVBoxLayout()
        settings_group.setLayout(settings_layout)
        layout.addWidget(settings_group)
        
        self.auto_connect_check = QCheckBox("启动时自动连接数据库")
        self.auto_start_tcp_check = QCheckBox("启动时自动启动TCP服务")
        settings_layout.addWidget(self.auto_connect_check)
        settings_layout.addWidget(self.auto_start_tcp_check)
        
        self.save_btn = QPushButton("保存设置")
        self.save_btn.clicked.connect(self.save_settings)
        settings_layout.addWidget(self.save_btn)
        
        # 初始化TCP模式
        self.change_tcp_mode(self.mode_combo.currentText())
    
    def change_tcp_mode(self, mode_text):
        """切换TCP工作模式"""
        if mode_text == "TCP服务端":
            self.tcp_mode = "server"
            self.server_frame.show()
            self.client_frame.hide()
        else:
            self.tcp_mode = "client"
            self.server_frame.hide()
            self.client_frame.show()
    
    def browse_db(self):
        """浏览数据库文件"""
        path, _ = QFileDialog.getOpenFileName(
            self, "选择Access数据库", "", "Access数据库 (*.mdb *.accdb)"
        )
        if path:
            self.db_path_input.setText(path)
            self.refresh_tables()
    
    def refresh_tables(self):
        """刷新表列表"""
        if not self.db_manager.connect(self.db_path_input.text()):
            return
        
        self.table_combo.clear()
        if self.db_manager.table_info:
            self.table_combo.addItems(self.db_manager.table_info.keys())
    
    def test_connection(self):
        """测试数据库连接"""
        if not self.db_manager.connect(self.db_path_input.text()):
            QMessageBox.warning(self, "错误", "数据库连接失败，请检查日志")
            return
        
        QMessageBox.information(
            self, "成功", 
            f"数据库连接成功!\n\n包含的表:\n" + 
            "\n".join(self.db_manager.table_info.keys())
        )
    
    def execute_query(self):
        """执行查询"""
        sn = self.scan_input.text().strip()
        if not sn:
            QMessageBox.warning(self, "警告", "请输入或扫描SN号码")
            return
        
        table = self.table_combo.currentText()
        if not table:
            QMessageBox.warning(self, "警告", "请选择表名")
            return
        
        self.result_display.clear()
        self.result_display.append(f"执行查询: SN='{sn}'\n表名: {table}\n")
        QApplication.processEvents()
        
        result = self.db_manager.query_with_all_methods(sn, table)
        
        if result['success']:
            self.result_display.append(f"查询方法: {result['method']}\n")
            self.result_display.append(f"找到 {len(result['data'])} 条记录:\n")
            
            for row in result['data']:
                row_str = " | ".join([f"{col}: {val}" for col, val in zip(result['columns'], row)])
                self.result_display.append(row_str)
        else:
            self.result_display.append("未找到匹配记录\n")
            self.result_display.append("调试信息:\n")
            self.result_display.append(f"尝试的查询方法: {result['method']}\n")
            self.result_display.append("表结构:\n")
            self.result_display.append("\n".join([
                f"{i+1}. {col}" 
                for i, col in enumerate(self.db_manager.get_table_columns(table))
            ]))
            self.result_display.append("\n示例数据:\n")
            for row in result['data']:
                row_str = " | ".join([f"{col}: {val}" for col, val in zip(result['columns'], row)])
                self.result_display.append(row_str)
            
            self.result_display.append("\n建议:")
            self.result_display.append("1. 检查SN字段名称是否正确")
            self.result_display.append("2. 检查数据是否包含特殊字符")
            self.result_display.append("3. 使用调试工具进一步检查")
        
        # 清除输入框并重新聚焦
        self.scan_input.clear()
        self.scan_input.setFocus()
    
    def full_inspection(self):
        """执行完整数据库检查"""
        if not self.db_manager.connect(self.db_path_input.text()):
            return
        
        self.debug_output.clear()
        self.debug_output.append("正在执行完整数据库检查...")
        QApplication.processEvents()
        
        self.debug_output.append("\n数据库结构:\n")
        for table, info in self.db_manager.table_info.items():
            self.debug_output.append(f"\n表名: {table}")
            self.debug_output.append(f"列数: {len(info['columns'])}")
            self.debug_output.append(f"行数: {info.get('row_count', '未知')}")
            self.debug_output.append("\n列名:")
            self.debug_output.append(", ".join(info['columns']))
            
            if info['possible_sn_columns']:
                self.debug_output.append("\n可能的SN字段:")
                self.debug_output.append(", ".join(info['possible_sn_columns']))
            else:
                self.debug_output.append("\n未识别到可能的SN字段")
            
            self.debug_output.append("\n示例数据:")
            for row in info.get('sample_data', []):
                row_str = " | ".join([f"{col}: {val}" for col, val in zip(info['columns'], row)])
                self.debug_output.append(row_str)
        
        self.debug_output.append("\n检查完成!")
    
    def execute_custom_sql(self):
        """执行自定义SQL"""
        sql = self.sql_input.toPlainText().strip()
        if not sql:
            QMessageBox.warning(self, "警告", "请输入SQL语句")
            return
        
        if not self.db_manager.connection:
            if not self.db_manager.connect(self.db_path_input.text()):
                QMessageBox.warning(self, "错误", "数据库未连接")
                return
        
        try:
            cursor = self.db_manager.connection.cursor()
            cursor.execute(sql)
            
            if sql.lower().startswith("select"):
                # 处理查询结果
                columns = [column[0] for column in cursor.description]
                rows = cursor.fetchall()
                
                self.sql_result.clear()
                self.sql_result.append(f"查询成功，返回 {len(rows)} 条记录\n")
                self.sql_result.append("列名: " + ", ".join(columns) + "\n")
                
                for row in rows:
                    row_str = " | ".join([f"{col}: {val}" for col, val in zip(columns, row)])
                    self.sql_result.append(row_str)
            else:
                # 处理非查询语句
                self.db_manager.connection.commit()
                self.sql_result.clear()
                self.sql_result.append("执行成功，影响行数: " + str(cursor.rowcount))
                
        except Exception as e:
            self.sql_result.clear()
            self.sql_result.append(f"SQL执行失败: {str(e)}")
    
    def start_server(self):
        """启动TCP服务器"""
        host = self.server_host_input.text()
        port = int(self.server_port_input.text())
        
        try:
            self.server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
            self.server_socket.bind((host, port))
            self.server_socket.listen(1)
            self.tcp_log.append(f"TCP服务器已启动，监听地址: {host}:{port}")
            self.start_server_btn.setEnabled(False)
            self.stop_server_btn.setEnabled(True)
            
            # 启动线程处理客户端连接
            threading.Thread(target=self.accept_connections, daemon=True).start()
        except Exception as e:
            self.tcp_log.append(f"服务器启动失败: {str(e)}")
    
    def accept_connections(self):
        while True:
            try:
                conn, addr = self.server_socket.accept()
                self.tcp_log.append(f"接受连接: {addr}")
                threading.Thread(target=self.handle_connection, args=(conn,), daemon=True).start()
            except Exception as e:
                if self.server_socket:
                    self.tcp_log.append(f"接受连接时出错: {str(e)}")
                break
    
    def handle_connection(self, conn):
        try:
            while True:
                data = conn.recv(1024)
                if not data:
                    break
                sn = data.decode().strip()
                self.tcp_log.append(f"收到数据: {sn}")
                self.scan_input.setText(sn)
                self.execute_query()
        except Exception as e:
            self.tcp_log.append(f"处理连接时出错: {str(e)}")
        finally:
            conn.close()
    
    def stop_server(self):
        """停止TCP服务器"""
        if self.server_socket:
            try:
                self.server_socket.close()
                self.tcp_log.append("TCP服务器已停止")
            except Exception as e:
                self.tcp_log.append(f"服务器停止时出错: {str(e)}")
            self.server_socket = None
            self.start_server_btn.setEnabled(True)
            self.stop_server_btn.setEnabled(False)
    
    def start_client(self):
        """启动TCP客户端"""
        host = self.client_host_input.text()
        port = int(self.client_port_input.text())
        
        try:
            self.client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
            self.client_socket.connect((host, port))
            self.tcp_log.append(f"TCP客户端已连接到 {host}:{port}")
            self.start_client_btn.setEnabled(False)
            self.stop_client_btn.setEnabled(True)
            
            threading.Thread(target=self.receive_data, daemon=True).start()
        except Exception as e:
            self.tcp_log.append(f"客户端连接失败: {str(e)}")
    
    def receive_data(self):
        try:
            while True:
                data = self.client_socket.recv(1024)
                if not data:
                    break
                sn = data.decode().strip()
                self.tcp_log.append(f"收到数据: {sn}")
                self.scan_input.setText(sn)
                self.execute_query()
        except Exception as e:
            self.tcp_log.append(f"接收数据时出错: {str(e)}")
        finally:
            self.stop_client()
    
    def stop_client(self):
        """停止TCP客户端"""
        if self.client_socket:
            try:
                self.client_socket.close()
                self.tcp_log.append("TCP客户端已断开连接")
            except Exception as e:
                self.tcp_log.append(f"客户端断开连接时出错: {str(e)}")
            self.client_socket = None
            self.start_client_btn.setEnabled(True)
            self.stop_client_btn.setEnabled(False)
    
    def load_settings(self):
        """加载设置"""
        self.db_path_input.setText(self.settings.value("db_path", ""))
        self.server_host_input.setText(self.settings.value("server/host", "0.0.0.0"))
        self.server_port_input.setText(self.settings.value("server/port", "12345"))
        self.client_host_input.setText(self.settings.value("client/host", ""))
        self.client_port_input.setText(self.settings.value("client/port", ""))
        self.auto_connect_check.setChecked(
            self.settings.value("auto_connect", "true") == "true"
        )
        self.auto_start_tcp_check.setChecked(
            self.settings.value("auto_start_tcp", "false") == "true"
        )
        
        # 加载TCP模式
        tcp_mode = self.settings.value("tcp_mode", "server")
        if tcp_mode == "client":
            self.mode_combo.setCurrentText("TCP客户端")
        else:
            self.mode_combo.setCurrentText("TCP服务端")
        
        if self.db_path_input.text():
            self.refresh_tables()
        
        # 自动启动TCP服务
        if self.auto_start_tcp_check.isChecked():
            if tcp_mode == "server":
                self.start_server()
            else:
                self.start_client()
    
    def save_settings(self):
        """保存设置"""
        self.settings.setValue("db_path", self.db_path_input.text())
        self.settings.setValue("server/host", self.server_host_input.text())
        self.settings.setValue("server/port", self.server_port_input.text())
        self.settings.setValue("client/host", self.client_host_input.text())
        self.settings.setValue("client/port", self.client_port_input.text())
        self.settings.setValue(
            "auto_connect", 
            "true" if self.auto_connect_check.isChecked() else "false"
        )
        self.settings.setValue(
            "auto_start_tcp", 
            "true" if self.auto_start_tcp_check.isChecked() else "false"
        )
        self.settings.setValue("tcp_mode", self.tcp_mode)
        
        QMessageBox.information(self, "成功", "设置已保存")

if __name__ == "__main__":
    app = QApplication(sys.argv)
    window = ScannerDebugUI()
    window.show()
    sys.exit(app.exec_())
